/*
 * Copyright (c)  2015~2020, xforceplus
 * All rights reserved.
 * Project:datacare-orm
 * Id: WhereTag.java   2020-10-10 21-47-29
 * Author: Evan
 */
package cn.datacare.orm.engine.tag;

import cn.datacare.orm.util.kit.StringKit;

import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: 2015~2020
 * </p>
 * <p>
 * Company/Department: xforceplus
 * </p>
 *
 * @author Evan
 * <b>Creation Time:</b> 2020-10-10 21-47-29
 * @since V1.0
 */
public class WhereTag extends TrimTag {
    /**
     * SQL Where :{@value}
     */
    private static final String WHERE = "WHERE";
    /***
     * And  & Or :{@value}
     */
    private static final String[] AND_OR_SPACE = new String[]{"AND ", "OR "};

    @Override
    public void render() {
        try {
            initTrimArgs(args);
            StringBuilder sb = buildTrimContent();
            this.ctx.byteWriter.writeString(sb.toString());
        } catch (IOException ie) {
            ie.printStackTrace();
        }
    }

    @Override
    protected void initTrimArgs(Object[] args) {
        if (args != null && args.length > 0) {
            for (Object arg : args) {
                if (arg instanceof Map) {
                    Map<String, Object> params = (Map<String, Object>) arg;
                    if (params.containsKey(PREFIX)) {
                        this.prefix = (String) params.get(PREFIX);
                    } else {
                        this.prefix = WHERE;
                    }
                    if (params.containsKey(PREFIX_OVERRIDES)) {
                        this.prefixOverrides = StringKit.split((String) params.get(PREFIX_OVERRIDES), SEPARATOR_CHAR);
                    } else {
                        this.prefixOverrides = AND_OR_SPACE;
                    }
                }
            }
        } else {
            this.prefix = WHERE;
            this.prefixOverrides = AND_OR_SPACE;
        }
    }
}
